import re
from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

class UsernameMobileAuthBackend(ModelBackend):
    '''
    自定义用户名或手机号验证
    '''
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断username传递的数据是否是一个手机号
        try:
            if re.match(r'^1[3-9]\d{9}$',username):
                # 如果是手机号，按照手机号查询用户对象
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None

        # 判断密码
        if user is not None and user.check_password(password):
            # 返回查询后的数据对象
            return user